import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList, ScrollView
} from "react-native";
import { GLOBAL } from '../../config/global';
import { style } from '../../theme/style';
import { Common } from '../../component/common/Common.js';
import { PageStatusIndex } from '../../component/page-status/PageStatusIndex';
import { RefuseModal } from '../../component/ModalVerifylComponent.js';
import { ProgressModal } from '../../components/common/ProgressModal';
import HTTP from '../../utils/http'
import { API, API_GENERATE } from '../../config/api';
import ToastUtil from '../../utils/toast';
import { CommonDialog } from '../../components/common/Dialog';
const scale = GLOBAL.SCALE;

export class RebateDetailPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			header: null
		}
	};
	constructor(props) {
		super(props);
		this.data = this.props.navigation.state.params.data;
		this.type = this.props.navigation.state.params.type;
		console.log(this.params, '99')
		let { applyId } = this.data || {};
		this.state = {
			tabIndex: 0,
			leftIndex: 0,
			modalVisibles: false,
			refreshIcon: false,
			status: 'data',
			resData: {

			},
			options: [],
			lightBoxData: {
				modalVisible: false,
				onClosePress: this._closeLightBox,
				title: '',
				rowDataList: [],
				status: 'data',
				refreshIcon: false,
			},
			modalVisible: false,
			alertRemark: ''
		}
		this.reload = true;
		this.pageParams = { // TODO
			applyId
		};
	}
	async componentWillMount() {
		await this._initPage();
	}

	// 初始化数据
	_initPage = async () => {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload,
		})
		let res = await HTTP.POST(API_GENERATE(API.REBARE_DETAIL), this.pageParams)
		if (res) {
			this.setState({
				status: res ? 'data' : 'empty',
				resData: res,
				refreshIcon: false
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}


	//切换
	_tabFn = (tabIndex) => {
		this.setState({
			tabIndex,
		})
	}
	// 刷新页面
	_onErrorRefresh = () => {
		this.reload = true;
		this._initPage();
	}

	// 审批
	approve = async () => {
		this.setState({ showRejectModal: false, });
		let requestParams = {
			businessKey: this.data.applyId,
			taskId: this.data.taskId,
			formKey: this.data.formKey,
			auditResult: this.auditResult,
			remark: this.remark,
		};
		let text = this.auditResult ? '同意' : '驳回';
		this.setState({ status: 'loading' });
		let res = await HTTP.POST(API_GENERATE(API.REBARE_AUDIT), requestParams);
		// this.requesting = false;
		if (res) {
			ToastUtil.showSuccess(`${text}成功`).then(() => {
				this.props.navigation.state.params.callback();
				this.props.navigation.goBack()
			})
		} else {
			this.setState({
				status: 'data'
			})
		}
	}
	// 审批流
	_getCheckApprove = async () => {
		//查询审批节点
		let responseData1
		responseData1 = await HTTP.POST(API_GENERATE(API.REBARE_AUDIT_DETAIL), {
			businessKey: this.data.applyId,
			processInstanceId: this.data.processInstanceId,
			bizObjType: 'REBATE_APPLY'
		});
		responseData1 = responseData1 && responseData1.map((item) => {
			if (item.auditResult == 9) {
				item.auditResultName = '操作';
			}
			return item;
		})
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = true;
		lightBoxData.title = '审批状态';
		lightBoxData.rowDataList = responseData1;
		this.setState({
			lightBoxData,
		})
	}

	_closeLightBox = () => {
		let { lightBoxData } = this.state;
		lightBoxData.modalVisible = false;
		this.setState({ lightBoxData });
	}

	_renderApprove = (item) => {
		return (
			<View style={styles.flexWhole}>
				{/* <View style={styles.flexWholeName}>
            <Text style={styles.flexWholeTitle} onPress={() => { this._getCheckApprove() }}>审批流</Text>
          </View> */}
				<View style={styles.itemDayTime}>
					<Text style={[styles.consent,]} onPress={() => {
						this.auditResult = 1;
						this.remark = '';
						this.setState({
							showRejectModal: true,
						})
						// this.consentCreate(item)
					}}>同意</Text>
					<Text style={styles.itemdown} onPress={() => {
						this.auditResult = 0;
						this.remark = '';
						this.setState({
							showRejectModal: true,
						})
					}}>驳回</Text>
				</View>
			</View>
		)
	}

	showRemark = (alertRemark) => {
		this.setState({
			modalVisible: true,
			modalTitle: '备注',
			alertRemark
		})
	}

	listOne = () => {
		let { resData, leftIndex } = this.state;
		let { groupItemList } = resData || []
		let data = groupItemList[leftIndex] || {}
		return (
			<View>
				{
					groupItemList && groupItemList.length > 0 ?
						<View style={styles.listBox}>
							<View style={styles.listLeft}>
								{groupItemList.map((item, index) => {
									return (
										<TouchableOpacity
											style={leftIndex == index ? styles.leftItemActive : styles.leftItem}
											onPress={() => {
												this.setState({
													leftIndex: index
												})
											}}
											key={index}
										>
											<Text style={leftIndex == index ? styles.leftTextActive : styles.leftText}>
												{item.groupName}
											</Text>
										</TouchableOpacity>
									)
								})}
							</View>
							<ScrollView style={styles.listRight} horizontal={true}>
								<View>
									<Text style={{ color: '#000', fontWeight: '600' }}>产品：{data.groupName}</Text>
									<View style={styles.table}>
										<View style={styles.tableTitle}>
											<Text style={{ color: '#000', fontSize: 12 * scale, marginRight: 39 * scale }}>区域</Text>
											<Text style={{ color: '#000', fontSize: 12 * scale, marginRight: 40 * scale }}>执行量（吨）</Text>
											<Text style={{ color: '#000', fontSize: 12 * scale }}>返利金额（元/吨）</Text>
										</View>
										{data.companyItemList ? data.companyItemList.map((item, j) => {
											return (
												<View style={styles.tableContent} key={j}>
													<Text style={{ fontSize: 12 * scale, color: '#6D8496', marginBottom: 14 * scale }}>{item.companyName}</Text>
													{item.rebateItemList.map((i, k) => {
														return (
															<View style={styles.tableTextBox} key={k}>
																<Text style={{ color: '#000', fontSize: 14 * scale, marginRight: 29 * scale, fontWeight: '600', width: 38 * scale }}>
																	{i.regionName}
																</Text>
																<Text style={{ color: '#000', fontSize: 14 * scale, marginRight: 15 * scale, fontWeight: '600', width: 50 * scale }}>
																	{i.exeQuantity}
																</Text>
																<View style={{ flexDirection: 'row', alignItems: 'center', marginRight: 5 * scale }}>
																	<Text style={[styles.priceType, i.priceType == 2 ? { color: '#FA6400', backgroundColor: '#FBEFE8' } : i.priceType == 1 ? { color: '#85C0EC', backgroundColor: '#ECF7FF' } : { color: '#008173', backgroundColor: '#87ddd8' }]}>
																		{i.priceType == 2 ? '升贴水' : i.priceType == 1 ? '一口价' : '全部'}
																	</Text>
																	<Text style={{ color: '#CA0202', fontSize: 14 * scale, fontWeight: '600', width: 45 * scale }}>
																		¥{i.rebatePrice}
																	</Text>
																</View>
																<TouchableOpacity onPress={() => { this.showRemark(i.remark || '无') }}>
																	<Text style={{ color: '#0091FF', fontSize: 14 * scale, fontWeight: '600', marginRight: 2 * scale, }}>
																		【备】
													</Text>
																</TouchableOpacity>

																<TouchableOpacity onPress={() => {
																	this.props.navigation.navigate('RebateRulePage', {
																		ruleItemList: i.ruleItemList,
																		attachmentFileList: i.attachmentFileList
																	})
																}}>
																	<Text style={{ color: '#0091FF', fontSize: 14 * scale, fontWeight: '600' }}>【规则】</Text>
																</TouchableOpacity>
															</View>
														)
													})
													}
												</View>
											)
										}) :
											null
										}
									</View>
								</View>
							</ScrollView>
						</View> : <Text style={{ marginTop: 25 * scale, paddingHorizontal: 20 * scale }}>暂无数据</Text>
				}
			</View>
		)
	}
	listTwo = () => {
		let { resData } = this.state;
		return (
			<View style={{ marginTop: 25 * scale, paddingHorizontal: 20 * scale }}>
				{resData.attachmentFileList ? resData.attachmentFileList.map((item, index) => {
					return (
						<TouchableOpacity key={index} onPress={() => { this.props.navigation.navigate('ContractPdfPage', { finalFileId: item.fileId, title: item.fileName }) }}>
							<Text style={styles.fileText}>
								【{item.fileName}】
								</Text>
						</TouchableOpacity>
					)
				}) :
					<Text>暂无附件</Text>
				}
			</View>
		)
	}
	render() {
		let { tabIndex, status, showRejectModal, lightBoxData, resData, modalVisible, alertRemark } = this.state
		let { applyId, rebateMonth, submitBy, submitTime, remark, organName } = resData
		if (rebateMonth) {
			rebateMonth = rebateMonth.slice(4)
			if (Number(rebateMonth) >= 10) {
				rebateMonth = rebateMonth
			}
			else {
				rebateMonth = rebateMonth.slice(1)
			}
		}
		this.TAB = [
			{
				name: rebateMonth ? rebateMonth + '月优惠明细' : '1月优惠明细',
				id: 0,
			}, {
				name: '附件信息',
				id: 1,
			}
		]
		return (
			<View style={styles.container}>
				<View style={styles.headBox}>
					<View style={styles.topBox}>
						<Common type="headLeft" onPress={() => { this.props.navigation.goBack() }} color='#fff' />
						<Text style={styles.topTitle}>客户返利</Text>
						<TouchableOpacity style={styles.flexWholeName} onPress={() => { this._getCheckApprove() }}>
							<Text style={styles.flexWholeTitle}>审批流</Text>
						</TouchableOpacity>
					</View>
				</View>
				<View style={styles.topFlexBox}>
					<View style={styles.flexBox}>
						<Text style={styles.flexTitle}>申请ID：</Text>
						<Text style={styles.flexText}>{applyId || '-'}</Text>
					</View>
					<View style={styles.flexBox}>
						<Text style={styles.flexTitle}>返利执行：</Text>
						<Text style={styles.flexText}>{rebateMonth ? rebateMonth + '月' : '-'}</Text>
					</View>
					<View style={styles.flexBox}>
						<Text style={styles.flexTitle}>提交人(部门)：</Text>
						<Text style={styles.flexText}>{submitBy ? submitBy + '（' + organName + '）' : '-'}</Text>
					</View>
					<View style={styles.flexBox}>
						<Text style={styles.flexTitle}>提交时间：</Text>
						<Text style={styles.flexText}>{submitTime ? submitTime : '-'}</Text>
					</View>
					<View style={styles.flexBox}>
						<Text style={styles.flexTitle}>申请备注：</Text>
						<Text style={styles.flexText}>{remark ? remark : '-'}</Text>
					</View>
				</View>
				<View style={[styles.flexBusiness, styles.flexAccount]}>
				</View>
				<View style={styles.headTitleBox}>
					{this.TAB.map((items, index) => {
						return (
							<TouchableOpacity key={index} onPress={() => { this._tabFn(index) }} style={{ flex: 1 }}>
								<Text style={[styles.tabItems, tabIndex == index ? styles.tabItemActive : null]}>{items.name}
								</Text>
								{tabIndex == index ? (
									<Text style={{
										height: 2 * scale, backgroundColor: '#0E7FFD', flexDirection: 'row', marginHorizontal: 40 * scale
									}}>
									</Text>
								) : null
								}
							</TouchableOpacity>
						)
					})
					}
				</View>

				{status == 'data' ? <ScrollView style={{ flex: 1 }}>
					{tabIndex == '0' ?
						this.listOne()
						: null
					}
					{tabIndex == '1' ?
						this.listTwo()
						: null
					}
				</ScrollView>
					: null}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无数据'} onErrorPress={this._onErrorRefresh} />) : null
				}
				{this.type == 'noApply' ? null : this._renderApprove()}
				{/* 审批流 */}
				<ProgressModal {...lightBoxData} />
				<RefuseModal
					titleText={'审批意见'}
					placeholderText={this.auditResult ? '请输入同意原因' : null}
					propsDefaultValue={this.auditResult ? '审批同意' : '审批驳回'}
					visible={showRejectModal}
					btnPress={(text) => {
						this.remark = text;
						this.approve();
					}}
					bgPress={() => {
						this.setState({
							showRejectModal: false,
						});
					}} />
				<CommonDialog modalVisible={modalVisible} title={'备注'} text={alertRemark} onClosePress={() => { this.setState({ modalVisible: false }) }} />
			</View>
		)

	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
		// paddingBottom: 30 * scale
	},
	flexBusiness: {
		flexDirection: 'row',
		paddingTop: 10 * scale,
		backgroundColor: style.color.themeColor,
		paddingLeft: 28 * scale,
	},
	flexBox: {
		flexDirection: 'row',
		paddingTop: 10 * scale,
		width: 240 * scale
	},
	topFlexBox: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 28 * scale,
		paddingRight: 35 * scale
	},
	flexTitle: {
		fontSize: 12 * scale,
		color: '#ffffff',
		width: 90 * scale,
		textAlign: 'right'
	},
	flexText: {
		fontSize: 12 * scale,
		color: '#ffffff',
	},
	flexApply: {
		flexDirection: 'row',
		paddingTop: 10 * scale,
		justifyContent: 'space-between',
		backgroundColor: style.color.themeColor,
		paddingLeft: 28 * scale,
		paddingRight: 60 * scale,
	},
	flexAccount: {
		paddingBottom: 25 * scale,
	},
	headTitle: {
		paddingBottom: 25 * scale,
		backgroundColor: 'red'
	},
	headTitleBox: {
		marginTop: -15 * scale,
		borderTopLeftRadius: 10 * scale,
		borderTopRightRadius: 10 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: '#fff',
		backgroundColor: '#fff',
		width: '100%',
		flexDirection: 'row',
		justifyContent: 'space-around',
	},
	tabItems: {
		color: '#0E7FFD',
		fontSize: 12 * scale,
		// width: '35%',
		textAlign: 'center',
		marginTop: 20 * scale,
		opacity: .8,
		paddingRight: 5 * scale,
		paddingLeft: 5 * scale,
		paddingBottom: 10 * scale,
	},
	tabItemActive: {
		opacity: 1,
	},
	flexWhole: {
		flexDirection: 'row',
		alignItems: 'center',
		paddingVertical: 24 * scale,
		backgroundColor: '#F4F7FE'
	},
	flexWholeName: {
		borderWidth: 1,
		borderColor: '#fff',
		borderRadius: 15 * scale,
		paddingHorizontal: 16,
		paddingVertical: 6
	},
	flexWholeTitle: {
		fontSize: 11,
		color: '#fff'
	},
	itemDayTime: {
		justifyContent: 'flex-end',
		flex: 1,
		flexDirection: 'row'
	},
	consent: {
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		fontSize: 12 * scale,
		opacity: 1,
		color: '#ffffff',
		alignItems: 'center',
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		// marginRight: 0 * scale,
		flexDirection: 'row',
		backgroundColor: style.color.themeColor,
		overflow: 'hidden'
	},
	itemdown: {
		fontSize: 12 * scale,
		color: style.color.themeColor,
		alignItems: 'center',
		paddingRight: 20 * scale,
		paddingLeft: 20 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		borderWidth: 1 * scale,
		borderStyle: 'solid',
		borderColor: style.color.themeColor,
		borderRadius: 15 * scale,
		marginRight: 20 * scale,
		flexDirection: 'row',
		marginLeft: 10 * scale,
	},

	headBox: {
		paddingTop: 50 * scale,
		backgroundColor: style.color.themeColor,
		paddingBottom: 10 * scale,
	},
	topTitle: {
		fontSize: 18 * scale,
		color: '#fff',
		fontWeight: '600'
	},
	topBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		paddingHorizontal: 18
	},
	listLeft: {
		paddingTop: 64 * scale,
		width: 56 * scale,
		marginRight: 8 * scale
		// backgroundColor: 'red',
	},
	listRight: {
		paddingTop: 23 * scale,
	},
	listBox: {
		flexDirection: 'row'
	},
	leftItem: {
		width: 56 * scale,
		justifyContent: 'center',
		paddingLeft: 8 * scale,
		paddingVertical: 6 * scale,
		borderTopRightRadius: 30 * scale,
		borderBottomRightRadius: 30 * scale,
		borderWidth: 1 * scale,
		borderColor: '#0E7FFD',
		borderLeftWidth: 0,
		marginBottom: 20 * scale,

	},
	leftItemActive: {
		width: 56 * scale,
		justifyContent: 'center',
		paddingLeft: 8 * scale,
		paddingVertical: 6 * scale,
		borderTopRightRadius: 30 * scale,
		borderBottomRightRadius: 30 * scale,
		borderWidth: 1 * scale,
		borderColor: '#0E7FFD',
		borderLeftWidth: 0,
		marginBottom: 20 * scale,
		backgroundColor: '#0E7FFD',
	},
	leftText: {
		fontSize: 12 * scale,
		color: '#0E7FFD',
		width: 40 * scale,
		flexWrap: 'wrap'
	},
	leftTextActive: {
		fontSize: 12 * scale,
		color: '#fff',
		width: 40 * scale,
		flexWrap: 'wrap'
	},
	tableTitle: {
		flexDirection: 'row',
		paddingLeft: 11 * scale,
		marginTop: 18 * scale,
		marginBottom: 6 * scale
	},
	tableContent: {
		backgroundColor: '#F4F7FE',
		borderRadius: 5 * scale,
		paddingTop: 10 * scale,
		paddingHorizontal: 14 * scale,
		marginBottom: 10 * scale
	},
	tableTextBox: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 10 * scale
	},
	priceType: {
		fontSize: 10,
		paddingVertical: 2,
		// paddingHorizontal: 5,
		backgroundColor: '#FBEFE8',
		marginLeft: 5 * scale,
		marginRight: 4 * scale,
		width: 40 * scale,
		textAlign: 'center'
	},
	fileText: {
		fontSize: 14 * scale,
		fontWeight: '600',
		color: '#0091FF',
		marginBottom: 20 * scale,
	},
})